﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Biz.EF.Gateway.Total;
using Biz.EF.Platform.Gxt;
using Biz.Properties;
using Hjt212Parser;
using log4net;

namespace Biz.Process
{
    public class ProcessorDownlineData4Total
    {
        private static ILog Log = LogManager.GetLogger(typeof (ProcessorDownlineData4Total));
        public static void GenDownlineData2081(GatewayTotalContext gCtx, PlatformGxtContext pCtx, string content)
        {
            try
            {
                var mn = Parser.GetStringByKey("MN", content);
                if (string.IsNullOrEmpty(mn)) return;
                var mnTotal = MonitorAndTotalMnMap.GetTotalMnByMonitorMn(mn);
                if (string.IsNullOrEmpty(mnTotal)) return;
                var datatime = Parser.GetDateTimeByKey("DataTime", content);
                if (!datatime.HasValue) return;

                var now = DateTime.Now;
                if (datatime.Value.Day != now.Day) return;


                var sb = new StringBuilder();
                sb.Append("ST=32;");
                var qn = datatime.Value.ToString("yyyyMMddHHmmssfff");
                sb.Append("QN=" + qn + ";");
                sb.Append("CN=2081;");
                sb.Append("PW=123456;");
                sb.Append("MN=" + mnTotal + ";");
                sb.Append("Flag=1;");
                sb.Append("CP=&&DataTime=" + datatime.Value.ToString("yyyyMMddHHmmss") + ";");
                sb.Append("Save_DayFlag=1;Save_MonFlag=1;");
                List<string> codes = Parser.GetPollutantCodes(content);

                var hour = new DateTime(datatime.Value.Year, datatime.Value.Month, datatime.Value.Day, datatime.Value.Hour, 0, 0);
                var nextHour = hour.AddHours(1);
                //放到循环外面，减少查询次数
                var realXaxis =
                    pCtx.xaxis_realtime.Where(t => t.MN.Equals(mnTotal))
                        .Where(t => t.datatime >= hour && t.datatime < nextHour)
                        .OrderByDescending(t => t.datatime)
                        .FirstOrDefault();

                var hourXaxis = pCtx.xaxis_hour.Where(t => t.MN.Equals(mnTotal))
                         .Where(t => t.datatime >= hour && t.datatime < nextHour)
                         .OrderByDescending(t => t.datatime)
                         .FirstOrDefault();

                var day = new DateTime(datatime.Value.Year, datatime.Value.Month, datatime.Value.Day, 0, 0, 0);
                var nextDay = day.AddDays(1);
                var dayXaxis = pCtx.xaxis_day.Where(t => t.MN.Equals(mnTotal))
                     .Where(t => t.datatime >= day && t.datatime < nextDay)
                     .OrderByDescending(t => t.datatime)
                     .FirstOrDefault();

                var month = new DateTime(datatime.Value.Year, datatime.Value.Month, 1, 0, 0, 0);
                var nextMonth = month.AddMonths(1);
                var monthXaxis = pCtx.xaxis_month.Where(t => t.MN.Equals(mnTotal))
                     .Where(t => t.datatime >= month && t.datatime < nextMonth)
                     .OrderByDescending(t => t.datatime)
                     .FirstOrDefault();

                var year = new DateTime(datatime.Value.Year, 1, 1, 0, 0, 0);
                var nextYear = year.AddYears(1);
                var yearXaxis = pCtx.xaxis_year.Where(t => t.MN.Equals(mnTotal))
                     .Where(t => t.datatime >= year && t.datatime < nextYear)
                     .OrderByDescending(t => t.datatime)
                     .FirstOrDefault();

                foreach (var code in codes)
                {
                    if (realXaxis != null)
                    {
                        var item =
                            pCtx.data_real_time.Where(t => t.ID == realXaxis.id)
                                .FirstOrDefault(t => t.pollutant.Equals(code));
                        if (item != null)
                        {
                            sb.Append(code + "-Rtd=" + item.rtd + ',');
                        }
                    }
                    if (hourXaxis != null)
                    {
                        var item =
                           pCtx.data_hour.Where(t => t.ID == hourXaxis.id)
                               .FirstOrDefault(t => t.pollutant.Equals(code));
                        if (item != null)
                        {
                            sb.Append(code + "-Min=" + item.min + ',');
                            sb.Append(code + "-Avg=" + item.avg + ',');
                            sb.Append(code + "-Max=" + item.max + ',');
                            sb.Append(code + "-Cou=" + item.cou + ',');
                        }
                    }
                    if (dayXaxis != null)
                    {
                        var item =
                           pCtx.data_day.Where(t => t.ID == dayXaxis.id)
                               .FirstOrDefault(t => t.pollutant.Equals(code));
                        if (item != null)
                        {
                            //sb.Append(code + "-Min=" + item.min + ',');
                            //sb.Append(code + "-Avg=" + item.avg + ',');
                            //sb.Append(code + "-Max=" + item.max + ',');
                            sb.Append(code + "-Cou-Day=" + item.cou + ',');
                        }
                    }
                    if (monthXaxis != null)
                    {
                        var item =
                           pCtx.data_month.Where(t => t.ID == monthXaxis.id)
                               .FirstOrDefault(t => t.pollutant.Equals(code));
                        if (item != null)
                        {
                            //sb.Append(code + "-Min=" + item.min + ',');
                            //sb.Append(code + "-Avg=" + item.avg + ',');
                            //sb.Append(code + "-Max=" + item.max + ',');
                            sb.Append(code + "-Cou-Mon=" + item.cou + ',');
                        }
                    }
                    sb.Append(code + "-Cou-Qut=0.00,");

                    if (yearXaxis != null)
                    {
                        var item =
                           pCtx.data_year.Where(t => t.ID == yearXaxis.id)
                               .FirstOrDefault(t => t.pollutant.Equals(code));
                        if (item != null)
                        {
                            //sb.Append(code + "-Min=" + item.min + ',');
                            //sb.Append(code + "-Avg=" + item.avg + ',');
                            //sb.Append(code + "-Max=" + item.max + ',');
                            sb.Append(code + "-Cou-Yea=" + item.cou + ';');
                        }
                    }
                    sb.Append("&&");
                    now = DateTime.Now;
                    if (Settings.Default.ToGatewayTotal)
                    {
                        var data =
                            gCtx.send_data_t
                                .Where(t => t.cn.Equals("2081"))
                                .Where(t => t.mn.Equals(mnTotal)).FirstOrDefault(t => t.qn.Equals(qn));
                        if (data == null)
                        {
                            data = new send_data_t
                            {
                                cn = "2081",
                                is_sent = false,
                                mn = mnTotal,
                                qn = qn,
                                send_string = Crc.WrapByCrc(sb.ToString(),"total"),
                                send_time = now,
                                sent_time = now
                            };
                            gCtx.send_data_t.Add(data);
                            gCtx.SaveChanges();
                        }
                    }
                    if (Settings.Default.ToPlatformGxt)
                    {
                        var data =
                            pCtx.gateway_sent_data
                                .Where(t => t.CN.Equals("2081"))
                                .Where(t => t.MN.Equals(mnTotal)).FirstOrDefault(t => t.QN.Equals(qn));
                        if (data == null)
                        {
                            data = new gateway_sent_data
                            {
                                IsProcessed = false,
                                IsValid = true,
                                MN = mnTotal,
                                ST = "32",
                                CN = "2081",
                                QN = qn,
                                SentString = Crc.WrapByCrc(sb.ToString(),"total"),
                                SentDatetime = now
                            };
                            pCtx.gateway_sent_data.Add(data);
                            pCtx.SaveChanges();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex);
            }

        }
    }
}
